import React, {Component, createRef} from 'react';
import {Avatar, Button, Form, Input, InputNumber, message, Modal, Upload} from 'antd'
import { addPrice, getMoney, editUser, getUser} from "../../api/user";
import { getUsers } from "../../actions/users";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import avatar from './avatar.jpeg'
import './personal.less'
import { connect} from 'react-redux'
import axios from "axios";

const mapStateToProps = (state,props) => {
    return {
        userInfo: state.user.info,
        userInfoNumber: state.user.info.number,
        userInfoAvatar: state.user.info.avater
    }
}

const mapDispatchToProps = (dispatch,props) => {
    return {
        getUser: (data) => {
            dispatch(getUsers(data))
        }
    }
}

@connect(mapStateToProps,mapDispatchToProps)
class PersonalCenter extends Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
        this.editFormRef = React.createRef();
        this.state = {
            visible: false,
            money: 0,
            inputNumber: '',
            loading: false,
            layout: {
                labelCol: {
                    span: 6,
                },
                wrapperCol: { span: 12 },
            }
        }
    }

    handleOk = (e) => {
        addPrice({money: this.state.inputNumber,number: this.props.userInfoNumber}).then(res => {
            message.success(res.msg);
            this.setState({
                visible: false
            })
            this.init()
        }).catch(err => {
            message.error(err)
        })
    }

    handleCancel = (e) => {
        this.setState({
            visible: false
        })
    }

    recharge = () => {
        this.setState({
            visible: true
        })
    }

    quickRecharge = (data) => {
        addPrice({money: data,number: this.props.userInfoNumber}).then(res => {
            message.success(res.msg);
            this.setState({
                visible: false
            })
            this.init()
        }).catch(err => {
            message.error(err)
        })
    }

    inputChange = (el) => {
        this.setState({
            inputNumber: el.target.value
        })
    }

    uploadEditAvater = ({file}) => {
        const data = new FormData();
        data.append("Token","7d366bf734da5f49ba55a59bb242d5c273bf0911:Wqdd0F4QLwgsQmdrt-cnAKLD2g8=:eyJkZWFkbGluZSI6MTU4Njk1NTIxOCwiYWN0aW9uIjoiZ2V0IiwidWlkIjoiNzE1NjU1IiwiYWlkIjoiMTY3ODc2NSIsImZyb20iOiJmaWxlIn0=");
        data.append('file',file);
        this.setState({
            loading: true
        })
        axios.post("http://up.imgapi.com/",data).then(res => {
            editUser({number: this.props.userInfoNumber, avater: res.data.linkurl}).then(res => {
                console.log(res.msg);
            })
            getUser({number: this.props.userInfoNumber}).then(res => {
                this.props.getUser(res.data)
                if (JSON.parse(window.localStorage.getItem('remember'))){
                    window.localStorage.setItem('isUserLogin',JSON.stringify(true))
                    window.localStorage.setItem('userInfo',JSON.stringify(res.data))
                }else{
                    window.sessionStorage.setItem('isUserLogin',JSON.stringify(true))
                    window.sessionStorage.setItem('userInfo',JSON.stringify(res.data))
                }
            })
        }).finally(() => {
            this.setState({
                loading: false
            })
        })
    }

    //上传前检验
    beforeUpload = (file) => {
        const limt = file.size/1024/1024 > 10;
        if (limt){
            message.error('文件大小超过10m,请重新选择');
            this.onRemove(file)
            return false;
        }
    }

    //删除不符合的文件
    onRemove = (fileList) => {
        this.setState({
            filelist: this.state.filelist.filter(item => {
                return item.name !== fileList.name
            })
        },() => {
            this.addFormRef.current.setFieldsValue({
                avater: '',
            })
        })
    }

    onChange = (file) => {
        this.setState({
            filelist: file.filelist
        })
    }

    modifyInfo = async () => {
        await editUser({...this.editFormRef.current.getFieldsValue()}).then(res => {
            console.log(res.msg);
            message.success(res.msg)
        })
        await getUser({number: this.props.userInfoNumber}).then(res => {
            this.props.getUser(res.data)
            if (JSON.parse(window.localStorage.getItem('remember'))){
                window.localStorage.setItem('isUserLogin',JSON.stringify(true))
                window.localStorage.setItem('userInfo',JSON.stringify(res.data))
            }else{
                window.sessionStorage.setItem('isUserLogin',JSON.stringify(true))
                window.sessionStorage.setItem('userInfo',JSON.stringify(res.data))
            }
        })
    }

    init = () => {
        getMoney({number: this.props.userInfoNumber}).then(res => {
            this.setState({
                money: res.data.money
            })
        })
        this.editFormRef.current.setFieldsValue({
            number: this.props.userInfo.number,
            name: this.props.userInfo.name,
            age: this.props.userInfo.age,
            iphone: this.props.userInfo.iphone,
            identity: this.props.userInfo.identity,
            email: this.props.userInfo.email
        })
    }

    componentDidMount() {
        this.init();
    }

    render() {
        return (
            <div className='personal'>
                <div className='part1'>
                    <div className="left">
                        <div className="avatar">
                            <Upload
                                listType="picture-card"
                                showUploadList={false}
                                beforeUpload={this.beforeUpload}
                                onRemove={this.onRemove}
                                onChange={this.onChange}
                                fileList={this.state.filelist}
                                customRequest={this.uploadEditAvater}
                            >
                                {this.props.userInfoAvatar ? <div className='waiImg'><img className='img' src={this.props.userInfoAvatar} alt="avatar" style={{ width: '100%' }} /></div> : <div>
                                    {this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
                                    <div className="ant-upload-text">上传头像</div>
                                </div>}
                            </Upload>
                        </div>
                    </div>
                    <div className="right">
                        <Form
                            {...this.state.layout}
                            name="add_user"
                            className="add_user"
                            ref={this.editFormRef}
                            initialValues={{ remember: true }}
                        >
                            <ul>
                                <li>
                                    <Form.Item
                                        label='账号'
                                        name= 'number'
                                    >
                                        <Input disabled={true}/>
                                    </Form.Item>
                                </li>
                                <li>
                                    <Form.Item
                                        label="名字"
                                        name="name"
                                    >
                                        <Input placeholder='修改名字'/>
                                    </Form.Item>
                                </li>
                                <li>
                                    <Form.Item
                                        label="年龄"
                                        name="age"
                                    >
                                        <InputNumber placeholder='修改年龄'/>
                                    </Form.Item>
                                </li>
                                <li>
                                    <Form.Item
                                        label="电话"
                                        name="iphone"
                                    >
                                        <Input placeholder='修改电话'/>
                                    </Form.Item>
                                </li>
                                <li>
                                    <Form.Item
                                        label="身份证"
                                        name="identity"
                                    >
                                        <Input placeholder='修改身份证'/>
                                    </Form.Item>
                                </li>
                                <li>
                                    <Form.Item
                                        label="邮箱"
                                        name="email"
                                    >
                                        <Input placeholder='修改邮箱'/>
                                    </Form.Item>
                                </li>
                            </ul>
                        </Form>
                        <Button onClick={this.modifyInfo} className='mod_button'>保存</Button>
                    </div>
                </div>
                <div className='part2'>
                    <div className="left">
                        <div className="header">余额</div>
                        <div className="body">{this.state.money}</div>
                    </div>
                    <div className="right">
                        <Button type='primary' onClick={this.recharge}>
                            充值
                        </Button>
                    </div>
                </div>
                <Modal
                    title="充值界面"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    className='recharge'
                    onCancel={this.handleCancel}
                >
                    <input type="number" className='moneyInput' onChange={this.inputChange} ref={this.inputRef}/>
                    <br/>
                    <div className="chongzhi">
                        <div className='title'>快速充值</div>
                        <ul>
                            <li><Button onClick={this.quickRecharge.bind(this,30)}>30元</Button></li>
                            <li><Button onClick={this.quickRecharge.bind(this,50)}>50元</Button></li>
                            <li><Button onClick={this.quickRecharge.bind(this,100)}>100元</Button></li>
                            <li><Button onClick={this.quickRecharge.bind(this,150)}>200元</Button></li>
                        </ul>
                    </div>
                </Modal>
            </div>
        );
    }
}

export default PersonalCenter;